package com.inspinia.base.dao.config;

import com.inspinia.base.dao.db.CustomDataSource;
import com.inspinia.base.dao.db.DataSources;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 数据源工具类，主要是用于搜集系统中的所有数据源
 * Created by Vebeln on 2017/1/13.
 */
public class DataSourceUtil {

    private static Map<Object, Object> targetDataSources;

    public static Map<Object, Object> getDataSources() {
        if (targetDataSources == null) {
            targetDataSources = new HashMap();

            Reflections reflections =new Reflections(new ConfigurationBuilder()
                    .setUrls(ClasspathHelper.forPackage("com.inspinia"))
                    .setScanners(new SubTypesScanner())
                    .filterInputsBy(new FilterBuilder().include(".*").exclude(".*.xml").exclude(".*.properties")));

            Set<Class<? extends CustomDataSource>> subTypes = reflections.getSubTypesOf(CustomDataSource.class);
            for (Class<? extends CustomDataSource> subType : subTypes) {
                try {
                    CustomDataSource o = subType.newInstance();
                    DataSource dataSource = o.getDataSource();
                    DataSources oKey = o.getKey();
                    targetDataSources.put(oKey, dataSource);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    
                    throw new RuntimeException("get datasource fail", e);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException("get datasource fail", e);
                }
            }

//            获取实现了自定义数据源接口的实现类
////            ArrayList<Class> allInterfacesForClass = com.centnet.base.util.ClassUtil.getAllClassByInterface(CustomDataSource.class);
//            for (int i = 0; i < subTypes.size(); i++) {
//                Class<?> implClass = allInterfacesForClass.get(i);
//                try {
//                    CustomDataSource o = (CustomDataSource) implClass.newInstance();
//                    DataSource dataSource = o.getDataSource();
//                    DataSources oKey = o.getKey();
//                    targetDataSources.put(oKey, dataSource);
//                } catch (InstantiationException e) {
//                    e.printStackTrace();
//                    throw new RuntimeException("get datasource fail", e);
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                    throw new RuntimeException("get datasource fail", e);
//                }
//            }
        }
        return targetDataSources;
    }

}
